﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sahit.iSoilHotel.Infrastructure.Web.Caching;
using Sahit.iSoilHotel.Portal.ServiceProxy.Tavern.Models.Room;
using Sahit.iSoilHotel.Portal.ServiceProxy.TavernRoomServiceReference;
using AutoMapper;
using Sahit.iSoilHotel.Infrastructure.Web.Events;
using Sahit.iSoilHotel.Portal.ServiceProxy.Tavern.Models.Filter;
using Sahit.iSoilHotel.Portal.ServiceProxy.Common;
using System.Web.Mvc;

namespace Sahit.iSoilHotel.Portal.ServiceProxy.Tavern.Proxys.Room
{
    public class TavernRoomServiceProxy:ITavernRoomServiceProxy
    {
        #region Constants

        private const string TAVERNROOM_ALL_KEY = "Tavern.Room.All";
        private const string TAVERNROOM_BY_ID_KEY = "Tavern.Room.ID-{0}";
        private const string TAVERNROOM_BY_TYPE = "Tavern.Room.Type-{0}";


        #endregion

        private readonly ICacheManager cacheManager;
        private TavernRoomServiceClient tavernRoomService;
        private readonly IEventPublisher eventPublisher;

        public TavernRoomServiceProxy(ICacheManager cacheManager)
        {
            this.cacheManager = cacheManager;
        }

        public List<RoomTypeModel> GetRoomType()
        {
            return cacheManager.Get(CacheKeysContainer.TAVERN_ROOMTYPE_ALL, () =>
            {
                using (tavernRoomService = new TavernRoomServiceClient())
                {
                    return Mapper.Map<List<RoomTypeModel>>(tavernRoomService.GetRoomType());
                }
            });
        }

        public List<RoomModel> GetRoom(RoomFilterModel filter)
        {
            return cacheManager.Get(CacheKeysContainer.TAVERN_ROOM_ALL, () =>
            {
                using (tavernRoomService = new TavernRoomServiceClient())
                {
                    var filterDTO = Mapper.Map<RoomFilterDTO>(filter);
                    var rooms = tavernRoomService.GetRoom(filterDTO);
                    return Mapper.Map<List<RoomModel>>(rooms);
                }
            });
        }


        public List<BuildingModel> GetAllBuildings()
        {
            return cacheManager.Get(CacheKeysContainer.TAVERN_BUILDING_ALL, () =>
            {
                using (tavernRoomService = new TavernRoomServiceClient())
                {
                    var buildings = tavernRoomService.GetAllBuildings();
                    return Mapper.Map<List<BuildingModel>>(buildings);
                }
            });
        }

        public IList<SelectListItem> GetFloors(Guid buildingID)
        {
            var building = GetAllBuildings().Where(b => b.ID == buildingID).FirstOrDefault();
            return building.FloorOptions;
        }
    }
}
